package xdu.lz.stage2_design_pattern.chapter7_future_pattern;

import org.junit.Test;

/**
    Future          ->未来的一个凭据
    FutureTask      ->将调用逻辑进行了隔离
    FutureService   ->桥接Future和FutureTask
 */
public class SyncInvoker {


    /**
     * 方式1：尝试去获取结果
     * @throws InterruptedException
     */
    @Test
    public void tryGetRes() throws InterruptedException {
        FutureService<String> futureService = new FutureService<>();
        //匿名内部类，是FutureTask接口的实现类。也可以用lamda表达式
        Future<String> future = futureService.submit(new FutureTask<String>() {
            @Override
            public String call() {
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                return "FINISH";
            }
        });

        //尝试获取结果
        try {
            System.out.println(future.tryGet(1000));
        } catch (TimeOutException e) {
            System.out.println("任务并未完成，获取超时被捕获了");
        }


        //做其他事情
        System.out.println("=========");
        System.out.println("do other thing");
        Thread.sleep(3000);
        System.out.println("=========");

        //获取结果
        System.out.println(future.get());
    }

    /**
     * 方式2：回调函数推送回调结果
     */

    public static void main(String[] args) throws InterruptedException {
        FutureService<String> futureService = new FutureService<>();
        futureService.submit(new FutureTask<String>() {
            @Override
            public String call() {
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                return "FINISH";
            }
            //参数2是一个回调函数，等待着回调结果，打印出来
        },System.out::println);

        //做其他事情
        System.out.println("=========");
        System.out.println("do other thing");
        Thread.sleep(1000);
        System.out.println("=========");
    }
}
